package jd.se.returnrequest;

import jd.se.common.Utils;
import org.apache.ibatis.session.SqlSession;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

public class ReturnRequestService {
    public void insertRequest(ReturnRequest request){
        SqlSession sess = Utils.openSession();
        try{
            ReturnRequestDao dao = sess.getMapper(ReturnRequestDao.class);
            dao.insertReturnRequest(request);
            sess.commit();
        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("添加请求失败！",e);
        }finally {
            sess.close();
        }
    }

    public Map<String, Object> getReturnRequest(String to_id) {
        SqlSession sess = Utils.openSession();
        ReturnRequestDao returnRequestDao = sess.getMapper(ReturnRequestDao.class);
        List<ReturnRequestShow> returnRequestList = returnRequestDao.showRequests(to_id);
        List<ReturnRequestDto> returnRequestDtos = new ArrayList<>();
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置格式
        for(ReturnRequestShow ritem : returnRequestList){             //获得带格式的字符串
            returnRequestDtos.add(new ReturnRequestDto(ritem.getFrom_id(),ritem.getB_id(),ritem.getU_name(), ritem.getB_name(), format.format(ritem.getTime())));
        }
        Map<String, Object> requests = new HashMap<>();
        requests.put("list", returnRequestDtos);
        return requests;
    }

    public void confirmRequest(BInfo info){
        SqlSession sess = Utils.openSession();
        ReturnRequestDao returnRequestDao = sess.getMapper(ReturnRequestDao.class);
        Timestamp timestamp = returnRequestDao.getRequestTime(info);
        Date date = returnRequestDao.getReturnDate(info);
        // 扣除信用值
        if(timestamp.after(new Timestamp(date.getTime()))){
            returnRequestDao.deductCredit(info);
        }
        returnRequestDao.deleteBorrowInfo(info);
        returnRequestDao.deleteReturnRequest(info);
        sess.commit();
    }

    public void refuseRequest(BInfo bInfo) {
        SqlSession sess = Utils.openSession();
        ReturnRequestDao returnRequestDao = sess.getMapper(ReturnRequestDao.class);
        returnRequestDao.deleteReturnRequest(bInfo);
        sess.commit();
    }
}
